import axios from 'axios';
import { ElMessage } from 'element-plus';
import { TEST_URL, MO_URL, TOKEN } from '@/constant';
import { getItem } from '@/utils/storage';
import store from '@/store';

const request = axios.create({
  baseURL: TEST_URL,
  timeout: 10000,
});

request.defaults.withCredentials = true;

// 请求拦截器
request.interceptors.request.use((config) => {
  const handleConfig = { ...config }
  const token = getItem(TOKEN);
  handleConfig.headers.Authorization = token ? `Bearer ${token}` : '';
  return handleConfig;
});

let timeout = null;

// // 响应拦截器
request.interceptors.response.use(
  async (res) => {
    if (res.data.code === 403) {
      if (timeout) clearTimeout(timeout)
      ElMessage.error(res.data.message);
      timeout = setTimeout(() => { store.dispatch("user/logout"); }, 500)
    }
    if (res.data.code != '200' && res.config.responseType !== 'blob' && res.data !== '上传文件成功' && typeof res.data !== 'string')
      ElMessage.error(res.data.message);
    return res.data;
  },
  (error) => {
    if (error.response.status !== 200) ElMessage.error('服务端错误，请联系管理员');
  },
);


export default request;
